
//
//  VideoViewController.m
//  LuckyRadio
//
//  Created by JiaRui on 15/11/20.
//  Copyright © 2015年 chenjun. All rights reserved.
//

#import "VideoViewController.h"
#import "CustomerNetworking.h"
#import "VideoTableViewCell.h"
#import "VideoCollectionViewCell.h"
#import "MVClassModel.h"
#import "VideoPlayerViewController.h"
#import <MBProgressHUD.h>
#import "MJRefresh.h"

#define w self.view.frame.size.width
#define h self.view.frame.size.height
@interface VideoViewController ()<UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, MBProgressHUDDelegate>
@property (nonatomic, retain) UITableView * dayTable;
@property (nonatomic, retain) UICollectionView * mvCollectionView;
@property (nonatomic, retain) UISegmentedControl * seg;
@property (nonatomic, retain) NSMutableArray * segArr;
@property (nonatomic, retain) UIView * view1;
@property (nonatomic, retain) UIView * view2;
@property (nonatomic, retain) UIScrollView * bigScrollView;

@property (nonatomic, retain) MBProgressHUD *HUD;


@property (nonatomic, retain) NSMutableArray * totalArr;
@property (nonatomic, retain) NSMutableArray * mvArr;


//@property (nonatomic, retain) NSMutableArray * listArr;
//@property (nonatomic, retain) NSMutableArray * tagArr;
@end

@implementation VideoViewController
-(void)dealloc
{
    [_dayTable release];
    [_mvCollectionView release];
    [_seg release];
    [_segArr release];
    [_view1 release];
    [_view2 release];
    [_bigScrollView release];
    [_totalArr release];
    [_mvArr release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    //初始化
    self.totalArr = [NSMutableArray array];
    self.mvArr = [NSMutableArray array];
//    self.listArr = [NSMutableArray array];
//    self.tagArr = [NSMutableArray array];
    
    //创建Seg条
    [self createSeg];
    //创建背景View
    [self createScrollView];
    //创建两个视图
    [self createViews];
    
    
    //第一页页面创建
    [self createNew];
    //    第二页页面创建
    [self createMV];
    
    _offset = 1;

    
    //第一页数据解析
    [self loadDay:NO];
    //第二页数据解析
    [self loadMV:NO];
    
    [self header];
    [self footer];
    
}

-(void) header
{
    self.mvCollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self.mvArr removeAllObjects];
        _offset =  1;
        [self loadMV:NO];
    }];
    
}
-(void) footer
{
    self.mvCollectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self.mvCollectionView.mj_footer beginRefreshing];
        _offset += 1;
        [self loadMV:YES];
    }];
    
    self.dayTable.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self.dayTable.mj_footer beginRefreshing];
        _offset += 1;
        [self loadDay:YES];
    }];
    
}

- (void)loadMV:(BOOL)isMore
{
    NSString *frontUrl =@"http://api.dongting.com/song/video/type/0?order=1&";
    NSString * min = [NSString stringWithFormat:@"page=%ld", _offset];
    NSString *gidUrl = @"&size=12&app=ttpod&v=v8.1.1.2015110616&user_id=0&mid=iPhone5S&f=f234&s=s310&imsi=&hid=&splus=9.1&active=1&net=2&openudid=e97c1f17f916efa173065a10152c7506e65b60f7&idfa=5FBD2BF5-1484-4C9B-A138-4D9CE22EADB5&utdid=VkKezJUW5SwDAGga0yzrZnyO&alf=700606&bundle_id=com.ttpod.music&latitude=38.89679246042943&longtitude=121.5286685343515";
    NSString * totalUrl = [NSString stringWithFormat:@"%@%@%@", frontUrl, min, gidUrl];
    
    [CustomerNetworking customerWithURL:totalUrl andParamer:nil andBlock:^(id response) {
        if (isMore == NO) {
            if (!self.mvArr.count) {
                for (NSDictionary * dic in [response objectForKey:@"data"]) {
                    MVClassModel * model = [MVClassModel modelWithDictionary:dic];
                    [self.mvArr addObject:model];
                }
                [self.mvCollectionView reloadData];

            }
        }else
        {
        for (NSDictionary * dic in [response objectForKey:@"data"]) {
            MVClassModel * model = [MVClassModel modelWithDictionary:dic];
            [self.mvArr addObject:model];
        }
        [self.mvCollectionView reloadData];
        }
        [self.mvCollectionView reloadData];
        [self.mvCollectionView.mj_header endRefreshing];
        [self.mvCollectionView.mj_footer endRefreshing];
    }];
}
- (void)loadDay:(BOOL)isMore
{
    if (_offset == 1) {
        self.HUD = [[MBProgressHUD showHUDAddedTo:self.view animated:YES] retain];
        self.HUD.delegate = self;
        //显示的文字
        self.HUD.labelText = @"正在进行加载~";
    }
    NSLog(@"===%ld", _offset);
    NSString *frontUrl =@"http://api.dongting.com/channel/channel/mvs?";
    NSString * min = [NSString stringWithFormat:@"page=%ld", _offset];
    NSString *gidUrl = @"&size=5&app=ttpod&v=v8.1.1.2015110616&user_id=0&mid=iPhone5S&f=f234&s=s310&imsi=&hid=&splus=9.1&active=1&net=2&openudid=e97c1f17f916efa173065a10152c7506e65b60f7&idfa=5FBD2BF5-1484-4C9B-A138-4D9CE22EADB5&utdid=VkKezJUW5SwDAGga0yzrZnyO&alf=700606&bundle_id=com.ttpod.music&latitude=38.89679246042943&longtitude=121.5286685343515";
    NSString * totalUrl = [NSString stringWithFormat:@"%@%@%@", frontUrl, min, gidUrl];

    [CustomerNetworking customerWithURL:totalUrl andParamer:nil andBlock:^(id response) {
        if (isMore == NO) {
            if (!self.totalArr.count) {
                for (NSDictionary * dic in [response objectForKey:@"data"]) {
                    VideoModel * model = [VideoModel modelWithDictionary:dic];
                    [self.totalArr addObject:model];
                }
                [self.dayTable reloadData];

            }
        }else
        {
        for (NSDictionary * dic in [response objectForKey:@"data"]) {
            VideoModel * model = [VideoModel modelWithDictionary:dic];
            [self.totalArr addObject:model];
        }
        [self.dayTable reloadData];
        }
        [self.dayTable reloadData];
        [self.dayTable.mj_footer endRefreshing];
    }];
    
    [self.HUD hide:YES];

}
- (void)createMV
{
    UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc]init];
    self.mvCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view2.frame.size.height) collectionViewLayout:flowLayout];
    self.mvCollectionView.backgroundColor = [UIColor clearColor];
    self.mvCollectionView.delegate = self;
    self.mvCollectionView.dataSource = self;
    self.mvCollectionView.showsHorizontalScrollIndicator = NO;
    [self.view2 addSubview:self.mvCollectionView];
    [_mvCollectionView release];
    [self.mvCollectionView registerClass:[VideoCollectionViewCell class] forCellWithReuseIdentifier:@"readIden"];
}


//返回最小的左右间距
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(w / 2, 215);
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (_mvArr.count) {
        return self.mvArr.count;
    }
    return 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_mvArr.count) {
        VideoCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"readIden" forIndexPath:indexPath];
        MVClassModel * model = [self.mvArr objectAtIndex:indexPath.item];
        cell.model = model;
        return cell;
    }
    else {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"nullCell" forIndexPath:indexPath];
        return cell;
    }
    
    return nil;
    

}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_mvArr.count) {
        VideoPlayerViewController * detail = [[VideoPlayerViewController alloc]init];
        VideoModel * model = [self.mvArr objectAtIndex:indexPath.row];
        detail.vid = model.ID;
        [self presentViewController:detail animated:YES completion:nil
         ];
    }
}


- (void)createNew
{
    self.dayTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view1.frame.size.height) style:UITableViewStylePlain];
    self.dayTable.delegate = self;
    self.dayTable.dataSource = self;
    [self.view1 addSubview:self.dayTable];
    [_dayTable release];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_totalArr.count) {
       return self.totalArr.count;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 320;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_totalArr.count) {
        VideoTableViewCell * cell = [VideoTableViewCell VideoTableViewCellWithTableView:tableView];
            cell.backgroundColor = [UIColor clearColor];
        cell.model = [self.totalArr objectAtIndex:indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_totalArr.count) {
        VideoPlayerViewController * detail = [[VideoPlayerViewController alloc]init];
        VideoModel * model = [self.totalArr objectAtIndex:indexPath.row];
        detail.vid = model.ID;
        [self presentViewController:detail animated:YES completion:nil
         ];
    }
}

#pragma mark  创建seg
-(void)createSeg
{
    self.segArr = [NSMutableArray arrayWithObjects:@"每日首发", @"最新MV", nil];
    //创建一个UISegmentedControl
    self.seg = [[UISegmentedControl alloc]initWithItems:self.segArr];
    self.seg.frame = CGRectMake(0, 0, self.view.frame.size.width, 30);
    self.seg.tintColor = [UIColor blackColor];
    [self.seg addTarget:self action:@selector(changeAction:) forControlEvents:UIControlEventValueChanged];
    self.seg.selectedSegmentIndex = 0;
    [self.view addSubview:self.seg];
    [_seg release];
    
}
#pragma mark  seg点击事件实现
- (void)changeAction:(UISegmentedControl *)seg
{
    switch (seg.selectedSegmentIndex) {
        case 0:
            self.bigScrollView.contentOffset = CGPointMake(0, 0);
            break;
        case 1:
            self.bigScrollView.contentOffset = CGPointMake(self.view.frame.size.width, 0);
            break;
        default:
            break;
    }
    
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if ([[NSString stringWithFormat:@"%@", [scrollView class]] isEqualToString:@"UIScrollView"]) {
        self.seg.selectedSegmentIndex = self.bigScrollView.contentOffset.x / self.view.frame.size.width;
    }
    
}
#pragma mark 背景滑动视图创建
-(void)createScrollView
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.bigScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 30, self.view.frame.size.width, self.view.frame.size.height - 30  - 64)];
    //可滚动区域
    self.bigScrollView.contentSize = CGSizeMake(self.view.frame.size.width * 2, 0);
    self.bigScrollView.delegate = self;
    //边界不回弹
    self.bigScrollView.bounces = NO;
    self.bigScrollView.pagingEnabled = YES;
    //关闭垂直滚动条
    self.bigScrollView.showsVerticalScrollIndicator = NO;
    self.bigScrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.bigScrollView];
    [self.bigScrollView release];
}

#pragma mark  创建两个独立的视图
-(void)createViews
{
    self.view1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.bigScrollView.frame.size.height)];
    //创建
    self.view2 = [[UIView alloc]initWithFrame:CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, self.bigScrollView.frame.size.height)];
    [self.bigScrollView addSubview:self.view1];
    [self.bigScrollView addSubview:self.view2];
    [_view1 release];
    [_view2 release];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
